package com.cykj.management.activity;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.cykj.management.R;
import com.cykj.management.common.MyLog;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RequestListener;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechEvent;
import com.iflytek.cloud.VoiceWakeuper;
import com.iflytek.cloud.WakeuperListener;
import com.iflytek.cloud.WakeuperResult;
import com.iflytek.cloud.util.ResourceUtil;
import com.iflytek.cloud.util.ResourceUtil.RESOURCE_TYPE;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

import android.content.Context;

public class WeakActivity {

    public static final String TAG = WeakActivity.class.getSimpleName();

    private static WeakActivity instance;
    // 语音唤醒对象
    private VoiceWakeuper mIvw;
    // 唤醒结果内容
    private String resultString;
    /**
     * 门限值越高，则要求匹配度越高，才能唤醒
     * 值范围：[0，3000]
     * 默认值：1450
     */
    private int curThresh = 1450;
    /**
     * 持续唤醒支持参数：
     * 0：单次唤醒
     * 1：循环唤醒
     * 默认值：0
     */
    private String keep_alive = "1";
    private Context mContext;
    private Toast mToast;
    /**
     * 闭环优化网络模式有三种：
     * 模式0：关闭闭环优化功能
     * <p>
     * 模式1：开启闭环优化功能，允许上传优化数据。需开发者自行管理优化资源。
     * sdk提供相应的查询和下载接口，请开发者参考API文档，具体使用请参考本示例
     * queryResource及downloadResource方法；
     * <p>
     * 模式2：开启闭环优化功能，允许上传优化数据及启动唤醒时进行资源查询下载；
     * 本示例为方便开发者使用仅展示模式0和模式2；
     */
    private String ivwNetMode = "0";

    public static WeakActivity getInstance() {
        if (instance == null) {
            instance = new WeakActivity();
        }
        return instance;
    }

    public void init(Context context) {
        this.mContext = context;
        this.mIvw = mIvw;
        mToast = Toast.makeText(context, "", Toast.LENGTH_SHORT);
        // 初始化唤醒对象
        mIvw = VoiceWakeuper.createWakeuper(context, null);
        startListening();
    }

    public void startListening(){
        if (mIvw != null) {
            // 清空参数
            mIvw.setParameter(SpeechConstant.PARAMS, null);
            // 唤醒门限值，根据资源携带的唤醒词个数按照“id:门限;id:门限”的格式传入
            mIvw.setParameter(SpeechConstant.IVW_THRESHOLD, "0:" + curThresh + ";" + "1:" + curThresh);
            // 设置唤醒模式
            mIvw.setParameter(SpeechConstant.IVW_SST, "wakeup");
            // 设置持续进行唤醒
            mIvw.setParameter(SpeechConstant.KEEP_ALIVE, keep_alive);
            // 设置闭环优化网络模式
            mIvw.setParameter(SpeechConstant.IVW_NET_MODE, ivwNetMode);
            // 设置唤醒资源路径
            mIvw.setParameter(SpeechConstant.IVW_RES_PATH, getResource());
            // 设置唤醒录音保存路径，保存最近一分钟的音频
//            mIvw.setParameter(SpeechConstant.IVW_AUDIO_PATH, Environment.getDataDirectory().getPath() + "/msc/ivw.wav");
            mIvw.setParameter(SpeechConstant.IVW_AUDIO_PATH, "/data/user/0/com.cykj.management" + "/msc/ivw.wav");
            mIvw.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
            // 如有需要，设置 NOTIFY_RECORD_DATA 以实时通过 onEvent 返回录音音频流字节
            //mIvw.setParameter( SpeechConstant.NOTIFY_RECORD_DATA, "1" );
            // 启动唤醒
//            mIvw.setParameter(SpeechConstant.AUDIO_SOURCE, "-1");

            mIvw.startListening(mWakeuperListener);
            /*File file = new File(Environment.getExternalStorageDirectory().getPath() + "/msc/ivw1.wav");
			byte[] byetsFromFile = getByetsFromFile(file);
			mIvw.writeAudio(byetsFromFile,0,byetsFromFile.length);*/
            //mIvw.stopListening();
        }else {
            MyLog.e(TAG,"mIvm 初始化错误");
        }
    }


    private InitListener initListener = new InitListener() {
        @Override
        public void onInit(int i) {
            MyLog.d(TAG, "initListener " + i);
        }
    };

    // 查询资源请求回调监听
    private RequestListener requestListener = new RequestListener() {
        @Override
        public void onEvent(int eventType, Bundle params) {
            // 以下代码用于获取查询会话id，当业务出错时将会话id提供给技术支持人员，可用于查询会话日志，定位出错原因
            if (SpeechEvent.EVENT_SESSION_ID == eventType) {
                MyLog.d(TAG, "sid:" + params.getString(SpeechEvent.KEY_EVENT_SESSION_ID));
            }
        }

        @Override
        public void onCompleted(SpeechError error) {
            MyLog.d(TAG, "error:" + error.getErrorCode());
            if (error != null) {
                MyLog.d(TAG, "error:" + error.getErrorCode());
                showTip(error.getPlainDescription(true));
            }
        }

        @Override
        public void onBufferReceived(byte[] buffer) {
            try {
                String resultInfo = new String(buffer, "utf-8");
                MyLog.d(TAG, "resultInfo:" + resultInfo);

                JSONTokener tokener = new JSONTokener(resultInfo);
                JSONObject object = new JSONObject(tokener);

                int ret = object.getInt("ret");
                if (ret == 0) {
                    String uri = object.getString("dlurl");
                    String md5 = object.getString("md5");
                    MyLog.d(TAG, "uri:" + uri);
                    MyLog.d(TAG, "md5:" + md5);
                    showTip("请求成功");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    private WakeuperListener mWakeuperListener = new WakeuperListener() {

        @Override
        public void onResult(WakeuperResult result) {
            MyLog.d(TAG, "onResult");
            if (!"1".equalsIgnoreCase(keep_alive)) {
            }
            try {
                String text = result.getResultString();
                JSONObject object;
                object = new JSONObject(text);
                StringBuffer buffer = new StringBuffer();
                buffer.append("【RAW】 " + text);
                buffer.append("\n");
                buffer.append("【操作类型】" + object.optString("sst"));
                buffer.append("\n");
                buffer.append("【唤醒词id】" + object.optString("id"));
                buffer.append("\n");
                buffer.append("【得分】" + object.optString("score"));
                buffer.append("\n");
                buffer.append("【前端点】" + object.optString("bos"));
                buffer.append("\n");
                buffer.append("【尾端点】" + object.optString("eos"));
                resultString = buffer.toString();
            } catch (JSONException e) {
                resultString = "结果解析出错";
                e.printStackTrace();
            }
            MyLog.d(TAG, resultString);
            mIvw.stopListening();
            TtsActivity ttsActivity = TtsActivity.getInstance();
            ttsActivity.init(mContext);
            ttsActivity.tts_play("我在,你说");

            // 初始化合成对象
//            try {
//                Thread.sleep(1000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }


        }

        @Override
        public void onError(SpeechError error) {
            showTip(error.getPlainDescription(true));
            MyLog.e(TAG, error.getPlainDescription(true));
        }

        @Override
        public void onBeginOfSpeech() {
        }

        @Override
        public void onEvent(int eventType, int isLast, int arg2, Bundle obj) {
            switch (eventType) {
                // EVENT_RECORD_DATA 事件仅在 NOTIFY_RECORD_DATA 参数值为 真 时返回
                case SpeechEvent.EVENT_RECORD_DATA:
                    final byte[] audio = obj.getByteArray(SpeechEvent.KEY_EVENT_RECORD_DATA);
                    MyLog.i(TAG, "ivw audio length: " + audio.length);
                    break;
            }
        }

        @Override
        public void onVolumeChanged(int volume) {

        }
    };


    private String getResource() {
        final String resPath = ResourceUtil.generateResourcePath(mContext, RESOURCE_TYPE.assets, "ivw/" + this.mContext.getString(R.string.app_id) + ".jet");
        MyLog.d(TAG, "resPath: " + resPath);
        return resPath;
    }

    private void showTip(final String str) {

        mToast.setText(str);
        mToast.show();


    }

    public static byte[] getByetsFromFile(File file) {
        byte[] buffer = null;
        ByteArrayOutputStream bos = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            bos = new ByteArrayOutputStream();
            buffer = new byte[35244];
            int length = 0;
            while ((length = fis.read(buffer)) != -1) {
                bos.write(buffer, 0, length);
            }
            fis.close();
            bos.close();
        } catch (Exception e) {

        }
        return bos.toByteArray();//字节流转换为一个 byte数组
    }

    public void release() {
        if (mIvw != null) {
            mIvw.stopListening();
        }
    }
}